package com.peng.mvvm_wan

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.peng.mvvm_wan.base.BaseActivity
import com.peng.mvvm_wan.viewmodels.LoginModel
import com.peng.safety.utils.SnackUtil
import com.uestc.request.handler.Request
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : BaseActivity() {
    private lateinit var navController: NavController
    private var backTime = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        setTheme(R.style.CommonActivityTheme)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
        initViews()
        initNet()
    }

    private fun initViews() {
        val loginModel = ViewModelProvider(this).get(LoginModel::class.java)
        loginModel.loginInfo.observeForever { loginBean ->
            bottom_nav.visibility = if (loginBean.id > 0) View.VISIBLE else View.GONE
        }
        navController = Navigation.findNavController(this, R.id.nav_host_fragment)
        bottom_nav.setOnNavigationItemSelectedListener {
            navController.popBackStack()
            when (it.itemId) {
                R.id.listFragment -> navController.navigate(R.id.listFragment)
                R.id.searchFragment -> navController.navigate(R.id.searchFragment)
                else -> navController.navigate(R.id.meFragment)
            }
            true
        }
    }

    private fun initNet() {
        Request.init(this, BASE_URL) {
            okHttp {
                //配置okhttp
                it
            }

            retrofit {
                //配置retrofit
                it
            }
        }
    }

    override fun showLoading() {
        loadingView.show()
    }

    override fun hideLoading() {
        loadingView.hide()
    }

    override fun onBackPressed() {
        val current = System.currentTimeMillis()
        if (current - backTime > 1000) {
            SnackUtil.show("再按一次返回退出应用")
            backTime = current
        } else {
            super.onBackPressed()
        }

    }

}